<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stream Data with jQuery</title>
    <script src="../js/jquery/jquery-3.7.1.min.js"></script>
    <script src="../js/jquery-ui/jquery-ui.min.js"></script>
    <script src="../js/jquery/jquery.cookie-1.4.1.min.js"></script>
    <script src="../js/moment.js"></script>
    <script src="../js/custom-log.js"></script>
    <script src="../js/base.js"></script>
</head>
<body>
<h1>Stream Data Example</h1>
<button id="startStream">Start Stream</button>
<pre id="output"></pre>

<script>
    $(document).ready(function () {
        $('#startStream').click(function () {
            let url = `${DEEPSEEK_URL_PREFIX}/completions/stream`;
            let requestBody = JSON.stringify({
                messages: [
                    {
                        name: '我',
                        content: '等会一起玩王者?'
                    },
                    {
                        name: '吉祥',
                        content: '怎么还不来游戏？在忙吗!'
                    }
                ]
            });
            // 使用 XMLHttpRequest 接收流式数据
            const xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            let token = $.cookie(TOKEN_KEY);
            // 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Authorization', token);
            xhr.responseType = 'text'; // 设置响应类型为文本流

            let receivedData = '';

            xhr.onprogress = function (event) {
                // 实时处理接收到的数据
                const chunk = xhr.responseText.substring(receivedData.length);
                // logger.info('Received chunk:', chunk);
                receivedData = xhr.responseText;
                $('#output').append(chunk.replaceAll('data:', '').replace(/\n/g, '')); // 将数据块显示在页面上
            };

            xhr.onload = function () {
                if (xhr.status === 200) {
                    logger.log('Stream complete');
                } else {
                    logger.error('Error:', xhr.statusText);
                }
            };

            xhr.send(requestBody);
        });
    });
</script>
</body>
</html>